<style scoped>
.main {
  width: 100%;
  min-height: 100vh;
}
</style>
<!--  -->
<template>
  <div class="main">
    <BackendHeader v-if="$route.path.indexOf('backend/user') > -1" />
    <BackendDesignHeaderN v-else-if="$route.path.indexOf('backend/design') > -1" />
    <div v-loading="backendLoading" :element-loading-text="backendLoadingText"
      element-loading-spinner="el-icon-loading" style="padding-top: 48px;">
      <router-view />
    </div>
    <DialogTemplateGuide ref="dialogTemplateGuide" :editorThemeTemplate="editorThemeTemplate"/>
    <DialogEditorThemeTemplate ref="dialogEditorThemeTemplate" />
    <DialogPasswordNotice ref="dialogPasswordNotice" :passwordlongtime="passwordlongtime" :passwordtoshort="passwordtoshort"/>
    <!-- 还原中蒙版-->
    <IsrestoreMask ref="isrestore"/>
    <!-- AI小助手-->
    <!-- <AiAssistant ref="aiassistant" v-if="isAIopen"/> -->
  </div>
</template>

<script>
import BackendHeader from '@/components/header/BackendHeader.vue'
import BackendDesignHeaderN from '@/components/header/BackendDesignHeaderN.vue'
import DialogTemplateGuide from '@/pages/backend/guide/DialogTemplateGuide.vue'
import DialogEditorThemeTemplate from '@/components/common/design/dialog/DialogEditorThemeTemplate.vue'
import DialogPasswordNotice from '@/pages/backend/guide/DialogPasswordNotice.vue'
import IsrestoreMask from '@/pages/backend/restore/IsrestoreMask.vue'
import AiAssistant from '@/components/aiassistant/AiAssistant.vue'
import { mapGetters, mapState } from 'vuex'
import storage from '@/core/storage.js'
import Session from '@/core/session'
// import storageGuide from '@/core/storageGuide.js'
import * as functions from '@/core/functions.js'
import PubSub from 'pubsub-js'
import * as PubsubType from '@/config/pubsubtype.js'
import _ from 'lodash'
export default {
  computed: {
    ...mapGetters(['currentSite', 'currentSiteConfig']),
    ...mapState([
      'user'
    ]),
    backendLoading: function () {
      // return !(this.currentSiteConfig && parseInt(this.currentSiteConfig.status) === 1)
      return !(this.currentSiteConfig && (parseInt(this.currentSiteConfig.status) === 1 || parseInt(this.currentSiteConfig.status) === 0))
    },
    backendLoadingText: function () {
      let text = ''
      if (this.currentSiteConfig && parseInt(this.currentSiteConfig.status) === 2) {
        text = '站点' + (this.currentSite && this.currentSite.language ? '（' + this.currentSite.language.name + '）' : '') + '正在初始化！'
      } else if (this.currentSiteConfig && parseInt(this.currentSiteConfig.status) === 3) {
        text = '站点' + (this.currentSite && this.currentSite.language ? '（' + this.currentSite.language.name + '）' : '') + '正在复制！'
      }
      return text
    }
  },
  created () {
    PubSub.subscribe(PubsubType.PUBSUB_RESTORE_NOW, (event, top) => {
      this.$post('/host-backup-restore/isrestore').then(response => {
        if (response && response.runing === 1) {
          this.$refs['isrestore'].show()
        }
      })
    })
    PubSub.publish(PubsubType.PUBSUB_RESTORE_NOW)
    functions.agentInfo().then(agent => {
      let favicon = document.querySelector('link[rel="shortcut icon"]')
      if (parseInt(agent.loginAgentDomain) === 1) {
        document.title = agent.title + '-' + this.user.loginUserName
        if (favicon) {
          favicon.href = agent.faviconImgSrc
        }
      } else {
        document.title = '刺猬响站2.0-' + this.user.loginUserName
      }
    })
    // document.title = '刺猬响站2.0-' + this.user.loginUserName
    this.intervalSiteConfig(this.currentSiteConfig)

    // 用户密码长时间没改判断
    this.$post('/user/createdate-and-updatepassworddate').then(
      response => {
        let newdate
        if (response && response.updatepassworddate) {
          newdate = response.updatepassworddate
        } else if (response && response.createdate) {
          newdate = response.createdate
        } else {
          newdate = null
        }
        let nowdate = new Date().getTime()
        let timelimit = 180 * 24 * 60 * 60 * 1000
        if (newdate && nowdate - newdate > timelimit) {
          this.passwordlongtime = true
        } else {
          this.passwordlongtime = false
        }
        // 用户密码是否合规
        this.$post('/user/password-less-than-8-digits').then(
          response => {
            if (response && parseInt(response) === 1) {
              this.passwordtoshort = false
            } else {
              this.passwordtoshort = true
            }
            // 账户安全提醒
            let jsessionid = Session.jsessionid()
            let ispasswordnotice = storage.getItem(jsessionid)
            if (!ispasswordnotice && (this.passwordlongtime || this.passwordtoshort)) {
              this.$refs['dialogPasswordNotice'].show()
              storage.setItem(jsessionid, true)
            }
          }
        )
      }
    )

    // AI是否开启
    this.$post('/ai/is-open').then(response => {
      if (response === 1) {
        this.isAIopen = true
      }
    })
  },
  mounted () {
    let langxInit = this.currentSite.language.lanNo + 'langxInit' + this.currentSite.site.hostId
    let isShow = storage.getItem(langxInit)
    if (!isShow && this.$store.state.site.init === 0) {
      this.$refs['dialogTemplateGuide'].show()
      storage.setItem(langxInit, true)
    }
  },
  data () {
    return {
      // 密码长时间没改
      passwordlongtime: false,
      // 密码没超过8位
      passwordtoshort: false,
      // AI是否开启
      isAIopen: false
    }
  },
  watch: {
    // 通过监听状态的高边，加入定时器，要求间隔3秒钟获取当前的站点状态，成功后台对其页面进行刷新
    currentSiteConfig: {
      handler (newValue) {
        this.intervalSiteConfig(newValue)
      },
      deep: true
    }
  },
  methods: {
    intervalSiteConfig (siteConfig) {
      // console.log(siteConfig)
      if (siteConfig && parseInt(siteConfig.status) === 2) {
        // 制作定时器，不断的请求后台查看当前状态
        var interval = setInterval(() => {
          this.$post('/site/site-config-status').then(
            response => {
              if (response && parseInt(response) === 1) {
                let sconfig = _.cloneDeep(this.currentSiteConfig)
                sconfig.status = response.status
                // this.$store.dispatch('siteConfigChange', sconfig)
                this.$message.success('语点初始化完成！')
                setTimeout(() => {
                  window.location.reload()
                }, 2000)
                clearInterval(interval)
              }
            }
          )
        }, 3000)
      } else if (siteConfig && parseInt(siteConfig.status) === 3) {
        // 制作定时器，不断的请求后台查看当前状态
        let interval = setInterval(() => {
          this.$post('/site/site-config-status').then(
            response => {
              if (response && parseInt(response) === 1) {
                let sconfig = _.cloneDeep(this.currentSiteConfig)
                sconfig.status = response.status
                // this.$store.dispatch('siteConfigChange', sconfig)
                this.$message.success('语点复制完成！')
                setTimeout(() => {
                  window.location.reload()
                }, 2000)
                clearInterval(interval)
              }
            }
          )
        }, 3000)
      }
    },
    editorThemeTemplate () {
      this.$refs['dialogEditorThemeTemplate'].show(true)
    }
  },
  components: {
    BackendHeader,
    BackendDesignHeaderN,
    DialogTemplateGuide,
    DialogEditorThemeTemplate,
    DialogPasswordNotice,
    IsrestoreMask,
    AiAssistant
  }
}

</script>
